package com.ilop.sthome.mvp.present.device;

import android.content.Context;
import android.text.TextUtils;

import com.example.common.mvp.BasePresenterImpl;
import com.ilop.sthome.common.command.SendAutoCommand;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.device.SocketTimingContract;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.utils.AutomationDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.tools.ByteUtil;
import com.siterwell.familywellplus.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author skygge
 * @date 2020-04-06.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class SocketTimingPresenter extends BasePresenterImpl<SocketTimingContract.IView> implements SocketTimingContract.IPresent {

    private Context mContext;
    private String mRecommendId;
    private String mDeviceName;
    private int mDeviceId;
    private int mMid;
    private boolean isModify;
    private DeviceInfoBean mDevice;
    private AutomationBean mAutomation;

    private SendAutoCommand mSendSceneData;
    private String mAutoCode;

    public SocketTimingPresenter(Context mContext, String recommendId) {
        this.mContext = mContext;
        this.mRecommendId = recommendId;
    }

    @Override
    public String getDeviceInfo(String deviceName, int deviceId) {
        this.mDeviceName = deviceName;
        this.mDeviceId = deviceId;
        mDevice = DeviceDaoUtil.getInstance().findByDeviceId(mDeviceName, mDeviceId);
        DeviceInfoBean mDeviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        mSendSceneData = new SendAutoCommand(mContext, mDeviceInfoBean);
        return mDevice.getDevice_type();
    }

    @Override
    public boolean getAutomationInfo(int mid) {
        this.mMid = mid;
        if (mid == -1){
            isModify = false;
            mAutomation = new AutomationBean();
        }else {
            isModify = true;
            mAutomation = AutomationDaoUtil.getInstance().findAutomationByMid(mid, mDeviceName);
        }
        return isModify;
    }

    @Override
    public void sendTimingCode(String status, String action) {
        if(TextUtils.isEmpty(status)){
            mView.showMsg(mContext.getString(R.string.set_first));
            return;
        }else if (status.startsWith("0300")){
            mView.showMsg(mContext.getString(R.string.set_weekday));
            return;
        }
        String deviceIdCode = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(mDeviceId));
        String outputCode = mDevice.getDevice_type() + deviceIdCode + action;
        String finalCode = CoderUtils.getNewCode(mRecommendId, status, outputCode);
        String finalCRC = ByteUtil.stringToCRC(finalCode);
        if (isModify){
            String autoId = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(mMid));
            mAutoCode = autoId + finalCode + finalCRC;
            mSendSceneData.updateAutomation(mAutoCode.toUpperCase());
            mAutomation.setCode(mAutoCode);
            mAutomation.setCrcCord(finalCRC);
        }else {
            mAutoCode = "FFFF" + finalCode + finalCRC;
            mSendSceneData.increaseAutomation(mAutoCode.toUpperCase());
            mAutomation.setReserve(mRecommendId);
            mAutomation.setCode(mAutoCode);
            mAutomation.setCrcCord(finalCRC);
            mAutomation.setDeviceName(mDeviceName);
        }
    }

    @Override
    public void sendDeleteTimer() {
        mSendSceneData.deleteAutomation(mMid);
    }

    @Override
    public void onSendSuccess(boolean isModify, String autoId) {
        ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
        String finalCode = isModify ? mAutoCode : autoId + mAutoCode.substring(4);
        Runnable runnable = () -> CoderUtils.analysisFullCode(finalCode.toUpperCase(), mDeviceName);
        mExecutorService.execute(runnable);
        mView.finishActivity();
    }

    @Override
    public void onDeleteSuccess() {
        if(mMid>-1){
            AutomationDaoUtil.getInstance().deleteByMid(mMid, mDeviceName);
            mMid = -1;
            mView.finishActivity();
        }
    }

    @Override
    public String getModifyHourAndMinute() {
        String action = mAutomation.getCode().substring(26, 34);
        int hour = Integer.parseInt(action.substring(4, 6), 16);
        int min = Integer.parseInt(action.substring(6), 16);
        return hour + "," + min;
    }

    @Override
    public HashMap<Integer, Boolean> getModifyWeekData() {
        String action = mAutomation.getCode().substring(26, 34);
        String init_week = action.substring(2, 4);
        byte ds = ByteUtil.hexStr2Bytes(init_week)[0];
        byte f;
        HashMap<Integer, Boolean> isSelected = new HashMap<>();
        for(int i=0;i<7;i++){
            f =   (byte)((0x02 << i) & ds);
            isSelected.put(i, f!=0);
        }
        return isSelected;
    }

    @Override
    public int getModifySocketState() {
        String outputCode = mAutomation.getCode().substring(46, 48);
        if ("18".equals(mRecommendId)) {
            switch (outputCode) {
                case "20":
                    return 1;
                case "30":
                    return 0;
                case "40":
                    return 2;
                default:
                    return 0;
            }
        }else {
            switch (outputCode) {
                case "40":
                    return 0;
                case "50":
                    return 1;
                default:
                    return 0;
            }
        }
    }

    @Override
    public ArrayList<String> getHour() {
        ArrayList<String> items_hour = new ArrayList<>();
        for (int i = 0; i < 24; i ++) {
            String item = String.valueOf(i);
            if (item.length() == 1) {
                item = "0" + item;
            }
            items_hour.add(item);
        }
        return items_hour;
    }

    @Override
    public ArrayList<String> getMinute() {
        ArrayList<String> items_minute = new ArrayList<>();
        for (int i = 0; i < 60; i ++) {
            String item = String.valueOf(i);
            if (item.length() == 1) {
                item = "0" + item;
            }
            items_minute.add(item);
        }
        return items_minute;
    }

    @Override
    public String getTimerStatus(HashMap<Integer, Boolean> week, int hour, int min) {
        byte f = 0x00;
        for(int i=0;i< week.size();i++){
            if(week.get(i)){
                f = (byte)((0x02 << i) | f);
            }
        }
        String weekDay = ByteUtil.convertByte2HexString(f);
        String hourDay = CoderUtils.setCodeSupplement1Byte(Integer.toHexString(hour));
        String minuteDay = CoderUtils.setCodeSupplement1Byte(Integer.toHexString(min));
        return "03" + weekDay + hourDay + minuteDay;
    }

}
